package cn.tedu.weibo.exception;

import cn.tedu.weibo.result.JsonResult;
import cn.tedu.weibo.result.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

//@ControllerAdvice//全局异常处理器
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    //    @ExceptionHandler
////    @ResponseBody
//    public JsonResult doHandleRuntimeException(RuntimeException e){
//        System.out.println("出现了RuntimeException！");
//        return new JsonResult(Status.UNKNOWN_ERROR);
//    }
    @ExceptionHandler
//    @ResponseBody
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e){
        System.out.println("出现了参数不合法异常！");
        return new JsonResult(Status.OPERATION_FAILED,e.getMessage());
    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String message = e.getFieldError().getDefaultMessage();
        log.warn(message,e);
        return new JsonResult(Status.VALIDATE_FAILED,message);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage();
        message = message.substring(message.indexOf(":")+1).trim();
        log.warn(message,e);
        return new JsonResult(Status.VALIDATE_FAILED,message);
    }
    @ExceptionHandler
    public JsonResult doHandleException(Exception e){
        log.error(e.getMessage(),e);
        System.out.println("异常！");
        return new JsonResult(Status.UNKNOWN_ERROR,e.getMessage());
    }

}
